package org.victoria.market.service.imp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.SpellCheckResponse;
import org.apache.solr.common.SolrInputDocument;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.victoria.market.api.ISearcher;
import org.victoria.market.dao.DaoSupport;
import org.victoria.market.domain.Goods;
import org.victoria.market.domain.Suggestion;
import org.victoria.market.utils.SolrBeanHelper;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by thanatos on 15-9-12.
 */
@Service
public class ISearcherImp implements ISearcher.Iface {

    private static final Logger logger = LoggerFactory.getLogger("ISearcherImp");
    @Autowired
    SolrServer mSolrServer;
    @Autowired
    DaoSupport daoSupport;

    @Override
    public String searcher(String query, int pageNum) throws TException {
        try {
            logger.info(String.format("searcher query is %s", query));

            //索引历史记录
            Suggestion suggestion = new Suggestion();
            suggestion.setSuggest(query);

            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);

            //pinwords
            StringBuilder builder = new StringBuilder(query);
            String pinwords = "";
            String abbrwords = "";
            for (int i=0; i<builder.length(); i++){
                String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(builder.charAt(i), format);
                String py;
                if (pinyin!=null){
                    py = pinyin[0];
                }else{
                    py = builder.charAt(i)+"";
                }
                pinwords += py;
                abbrwords += py.charAt(0);
            }

            suggestion.setPinwords(pinwords);
            suggestion.setAbbrwords(abbrwords);

            logger.info(String.format("query>>>%s, pinwords>>>%s, abbrwords>>>%s", query, pinwords, abbrwords));

            mSolrServer.addBean(suggestion);
            mSolrServer.commit();

            //将所有结果取出来
            SolrBeanHelper<Goods> helper = SolrBeanHelper.instanicate(Goods.class)
                    .initQueryHighlight(query, 1, 10000000, 30)
                    .setHighlightFields("goods_title", "goods_keywords");

            List<Goods> results = helper.query(mSolrServer).getResults();

            List<Goods> products = null;

            if (results != null && results.size() > 0) {
                List<Long> ids = new ArrayList<>();

                for (Goods item : results) {
                    ids.add(item.getId());
                }
                products = daoSupport.openQueryHelper()
                        .setNameSpace("Goods.getAround").setValue(ids)
                        .dao().find();
            }

            JSONObject obj = new JSONObject();
            obj.put("results", results);
            obj.put("products", products);

            logger.info(">>>>>>>searcher query over <<<<<<<");

            return obj.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new TException(e);
        }
    }

    @Override
    public List<String> suggest(String query, int pageNum) throws TException {
        try {

            logger.info("suggest >>> query >>>" + query);

            List<Suggestion> slist = SolrBeanHelper.instanicate(Suggestion.class)
                    .initQueryNotHighlight(query + "*", 1, 10)
                    .query(mSolrServer)
                    .getResults();

            Set<Suggestion> sset = new HashSet<>(slist);

            List<String> alternatives = new ArrayList<>();
            for (Suggestion suggestion : sset) {
                SolrBeanHelper<Goods> helper = SolrBeanHelper.instanicate(Goods.class)
                        .initQuery(suggestion.getSuggest(), false, -1, -1)
                        .setQueryFields("goods_title");
                alternatives.add(suggestion.getSuggest() + "," + helper.query(mSolrServer).getDocumentCount());
            }
            return alternatives;
        } catch (Exception e) {
            e.printStackTrace();
            throw new TException(e);
        }
    }

    @Override
    public String pinyin(String xchar) throws TException {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(xchar.charAt(0));
        if (pinyin!=null){
            return pinyin[0].charAt(0)+"";
        }else{
            String fs = xchar.charAt(0)+"";
            if (fs.matches("[a-zA-Z]")){
                return fs;
            }
            return "其它";
        }
    }

}
